<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

    protected $_frontController;

    /**
     * Bootstrap autoloader for application resources
     *
     * @return Zend_Application_Module_Autoloader
     */
    protected function _initAutoload()
    {
        // Ensure front controller instance is present
        $this->bootstrap('frontController');
        $this->_frontController = $this->getResource('frontController');
        // Add autoloader empty namespace
        $autoLoader = new Zend_Application_Module_Autoloader(array(
            'namespace' => '', 'basePath' => APP_PATH));

        return $autoLoader;
    }

    protected function _initZFDebug()
    {
        if (APPLICATION_ENV !== 'development') {
            return;
        }
        $autoloader = Zend_Loader_Autoloader::getInstance();
        $autoloader->registerNamespace('ZFDebug_');

        $options = array(
            'jquery_path' => '/themes/appcore/js/jquery-1.7.2.min.js',
            'plugins' => array('Variables',
                'Html',
                'File' => array('base_path' => APP_PATH),
                'Memory',
                'Time',
                'Registry',
                'Exception')
        );

        // Instantiate the database adapter and setup the plugin.
        // Alternatively just add the plugin like above and rely on the autodiscovery feature.
        if ($this->hasPluginResource('db')) {
            $this->bootstrap('db');
            $db = $this->getPluginResource('db')->getDbAdapter();
            $options['plugins']['Database']['adapter'] = $db;
        }

        // Setup the cache plugin
        if ($this->hasPluginResource('cache')) {
            $this->bootstrap('cache');
            $cache = $this - getPluginResource('cache')->getDbAdapter();
            $options['plugins']['Cache']['backend'] = $cache->getBackend();
        }

        $debug = new ZFDebug_Controller_Plugin_Debug($options);

        $this->bootstrap('frontController');
        $frontController = $this->getResource('frontController');
        $frontController->registerPlugin($debug);
    }

    /**
     * Setup Database
     *
     * @return void
     */
    /*
     protected function _initDB()
     {}
    */

    /**
     * Setup logging
     *
     * @return void
     */
    protected function _initHelpers()
    {

    }

    /**
     * Setup View
     *
     * @return void
     */
    protected function _initView()
    {
        $view = new Zend_View();

        // Instantiate and add the helper in one go
        $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
        $viewRenderer->setView($view);
        $viewRenderer->setViewSuffix('phtml');

        // Initialise Zend_Layout's MVC helpers
        // by default with layout config option in ../configs/application.ini

        return $view;
    }

    /**
     * @Desc : Initial all viewer setting here
     *
     * @return : void
     */
    protected function _initViewSettings()
    {
        try {
            $config = Zend_Registry::get('configuration');
        } catch (Exception $e) {
            $this->_initConfig();
            $config = Zend_Registry::get('configuration');
        }

        $this->bootstrap('view');

        // Load view helper
        $this->view->addHelperPath('APPCore' . DS . 'View' . DS . 'Helper', 'APPCore_View_Helper');
    }

    /**
     * Setup Plugins
     *
     * @return void
     */
    protected function _initPlugins()
    {

    }

    /**
     * Setup Plugins
     *
     * @return void
     */
    protected function _initRoutes()
    {
        $routes = new Zend_Config_Xml(APP_PATH . DS . 'configs' . DS . 'routes.xml');
        // Get the front controller
        $front_controller = Zend_Controller_Front::getInstance();
        // Get the router
        $router = $front_controller->getRouter();
        // Load the site routes into the router
        $router->addConfig($routes, 'routes');
    }

    /**
     * Setup Plugins
     *
     * @return void
     */
    protected function _initControllers()
    {

    }

    /**
     * Add Controller Action Helpers
     */
    protected function _initActionHelpers()
    {
        Zend_Controller_Action_HelperBroker::addPath('APPCore' . DS . 'Controller' . DS . 'Action' . DS . 'Helper', 'APPCore_Controller_Action_Helper');
    }

    /**
     * Setup logging
     *
     * @return void
     */
    protected function _initLogs()
    {
        $this->bootstrap('log');
        $logs = $this->getPluginResource('log');
        Zend_Registry::set('logger', $logs->getLog());
    }

    /*     * **********************************************************
     * Here I'm loading my configuration file
    * and i am placing the returned object inside Zend registry
    * this is a bit like having it as a global variable
    * ********************************************************** */

    protected function _initConfig()
    {
        $configuration = new Zend_Config_Ini(APP_PATH . DS . 'configs' . DS . 'configuration.ini', 'bootstrap', array(
            'skipExtends' => false, 'allowModifications' => true));
        Zend_Registry::set('configuration', $configuration);
    }

    protected function _initViewHelpers()
    {
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $view->doctype('XHTML1_STRICT');
        $view->headMeta()->appendHttpEquiv('Content-Type', 'text/html;charset=utf-8');
    }

    /**
     * used for handling top-level navigation
     * @return Zend_Navigation
     */
    protected function _initNavigation()
    {
        $this->bootstrap('layout');
        $layout = $this->getResource('layout');
        $view = $layout->getView();
        $config = new Zend_Config_Xml(APP_PATH . '/configs/navigation.xml', 'nav');

        $container = new Zend_Navigation($config);

        $view->navigation($container);
    }

    /**
     * Run the application
     *
     * Checks to see that we have a default controller directory. If not, an
     * exception is thrown.
     *
     * If so, it registers the bootstrap with the 'bootstrap' parameter of
     * the front controller, and dispatches the front controller.
     *
     * @return void
     * @throws Zend_Application_Bootstrap_Exception
     */
    public function run()
    {
        $writeLog = 1;
        $this->_frontController->throwExceptions(false);
        if (in_array(APPLICATION_ENV, array('development', 'testing'))) {
            $writeLog = 0;
            $this->_frontController->throwExceptions(true);
        }
        try {
            $this->_frontController->dispatch();
        } catch (Zend_Exception $e) {
            $logger = Zend_Registry::get('logger');
            $request = $this->_frontController->getRequest();
            $params = $request->getParams();
            //unset($params['error_handler']);
            $message = $e->getMessage() . "\n" . $e->getTraceAsString() . "\n Param: \n" . var_export($params, true) . "\n";
            if ($writeLog) {
                $logger->log($message, Zend_Log::DEBUG);
            }
            echo '<pre>';
            print_R($message);
            echo '</pre>';
            exit();
        }
    }

}